package com.flyxiaozhu.erp.admin.controllers;

import com.flyxiaozhu.erp.admin.resps.GoodsResp;
import com.flyxiaozhu.erp.admin.resps.SchemaResp;
import com.flyxiaozhu.erp.core.entities.Goods;
import com.flyxiaozhu.erp.core.entities.GoodsSku;
import com.flyxiaozhu.erp.core.entities.GoodsTag;
import com.flyxiaozhu.erp.core.libs.Constants;
import com.flyxiaozhu.erp.core.libs.ErrorCode;
import com.flyxiaozhu.erp.core.libs.JSONResult;
import com.flyxiaozhu.erp.core.libs.SearchSpecification;
import com.flyxiaozhu.erp.core.repositories.GoodsAttrNameRepository;
import com.flyxiaozhu.erp.core.repositories.GoodsRepository;
import com.flyxiaozhu.erp.core.repositories.GoodsSkuRepository;
import com.flyxiaozhu.erp.core.repositories.GoodsTagRepository;
import com.flyxiaozhu.erp.core.services.GoodsCategoryService;
import com.flyxiaozhu.erp.core.services.GoodsSkuService;
import com.flyxiaozhu.erp.core.utils.BeanUtils;
import com.flyxiaozhu.erp.core.utils.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.access.annotation.Secured;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author flyxiaozhu
 * @date 2019-04-25 16:13
 */
@RestController
public class goodsRecycleController {
    @Autowired
    GoodsRepository goodsRepository;
    @Autowired
    GoodsSkuService goodsSkuService;
    @Autowired
    GoodsCategoryService goodsCategoryService;
    @Autowired
    GoodsTagRepository goodsTagRepository;
    @Autowired
    GoodsAttrNameRepository goodsAttrNameRepository;
    @Autowired
    GoodsSkuRepository goodsSkuRepository;

    @RequestMapping(value = "/goodsRecycle/select")
    @Secured("ROLE_GOODS_RECYCLE_SELECT")
    public JSONResult goodsList(HttpServletRequest request, @PageableDefault(sort = {"updateTime", "createTime"}, direction = Sort.Direction.DESC) Pageable pageable) {
        SearchSpecification<Goods> searchSpecification = new SearchSpecification<>(request);
        searchSpecification.setBeforeFilter((list, root, query, cb) -> {
            list.add(cb.equal(root.get("isDeleted"), true));
        });

        Page<Goods> goodsPage = goodsRepository.findAll(searchSpecification, pageable);

        if (goodsPage.getContent().size() == 0) {
            return new JSONResult().put("list", new ArrayList<>());
        }

        Map<Long, List<GoodsSku>> skusGroupByGoodsId = goodsSkuService.findByGoodsIdGroup();

        List<GoodsResp> resps = new ArrayList<>();
        for (Goods goods : goodsPage.getContent()) {
            goods.setGoodsSkus(skusGroupByGoodsId.get(goods.getId()));
            GoodsResp goodsResp = new GoodsResp();
            BeanUtils.copyProperties(goods, goodsResp);
            resps.add(goodsResp);
        }

        return new JSONResult(goodsPage, pageable.getPageNumber()).put("list", resps);
    }

    /**
     * 商品还原
     *
     * @param keys
     * @return
     */
    @RequestMapping(value = "/goodsRecycle/recycle")
    @Secured("ROLE_GOODS_RECYCLE_RECYCLE")
    public JSONResult recycle(@RequestParam String keys) {
        if (StringUtils.isBlank(keys)) {
            return new JSONResult(ErrorCode.NO_DATA, "参数错误");
        }
        String[] ids = keys.split(",");
        Map<Long, Goods> goodsMap = CollectionUtils.columnMap(goodsRepository.findAll(), Goods::getId);
        List<Goods> goodsList = new ArrayList<>();

        for (String id : ids) {
            Goods goods = goodsMap.get(Long.parseLong(id));
            if (goods == null) {
                return new JSONResult(ErrorCode.NO_DATA, "商品不存在");
            }
            goods.setExamineStatus(Constants.GOODS_EXAMINE_WAIT);
            goods.setStatus(Constants.GOODS_STATUS_NORMAL);
            goods.setIsDeleted(false);

            goodsList.add(goods);
        }
        goodsRepository.saveAll(goodsList);

        return new JSONResult().put("count", goodsList.size()).put("ids", ids);
    }

    /**
     * 商品删除
     *
     * @param keys
     * @return
     */
    @RequestMapping(value = "/goodsRecycle/delete")
    @Secured("ROLE_GOODS_RECYCLE_DELETE")
    @Transactional(rollbackFor = Exception.class)
    public JSONResult delete(@RequestParam String keys) {
        if (StringUtils.isBlank(keys)) {
            return new JSONResult(ErrorCode.NO_DATA, "参数错误");
        }
        List<Long> ids = CollectionUtils.parseSplitStr(keys, ",", Long::valueOf);

        goodsAttrNameRepository.deleteAllByGoodsIdIn(ids);
        goodsSkuRepository.deleteAllByGoodsIdIn(ids);
        goodsRepository.deleteAllByIdIn(ids);

        return new JSONResult().put("count", ids.size()).put("ids", ids);
    }

    /**
     * 获取配置信息
     *
     * @return
     */
    @RequestMapping(value = "/goodsRecycle/schema")
    public JSONResult schema() {
        // querySchema
        List<SchemaResp> querySchema = new ArrayList<>();

        // 商品分类
        SchemaResp categoriesObj = new SchemaResp();
        List<Map> options = new ArrayList<>();

        List<Map> categories = goodsCategoryService.getFormattedTypes(goodsCategoryService.getTree2());
        for (Map category : categories) {
            Map<String, Object> item = new HashMap<>();
            item.put("key", category.get("id"));
            item.put("value", category.get("name"));
            options.add(item);
        }

        categoriesObj.setKey("search_eq_categoryId");
        categoriesObj.setTitle("商品分类");
        categoriesObj.setDataType("varchar");
        categoriesObj.setShowType("select");
        categoriesObj.setOptions(options);

        querySchema.add(categoriesObj);

        // 商品标签
        SchemaResp tagsObj = new SchemaResp();
        List<Map> options2 = new ArrayList<>();
        List<GoodsTag> goodsTags = goodsTagRepository.findAll();
        for (GoodsTag goodsTag : goodsTags) {
            Map<String, Object> item = new HashMap<>();
            item.put("key", goodsTag.getId());
            item.put("value", goodsTag.getTitle());
            options2.add(item);
        }

        tagsObj.setKey("search_eq_tagsId");
        tagsObj.setTitle("商品标签");
        tagsObj.setDataType("varchar");
        tagsObj.setShowType("select");
        tagsObj.setOptions(options2);

        querySchema.add(tagsObj);

        // dataSchema
        List<SchemaResp> dataSchema = new ArrayList<>();

        SchemaResp categoriesObj2 = new SchemaResp();
        categoriesObj2.setKey("categoryId");
        categoriesObj2.setTitle("商品分类");
        categoriesObj2.setDataType("varchar");
        categoriesObj2.setShowType("select");
        categoriesObj2.setOptions(options);

        dataSchema.add(categoriesObj2);

        return new JSONResult().put("querySchema", querySchema).put("dataSchema", dataSchema);
    }
}
